#!/usr/bin/env python

import filecmp
import os
import re
import shutil

class CompareArgs:
    def __init__(self, dir1, dir2):
        self.dir1 = dir1
        self.dir2 = dir2
        self.dirpath = os.path.abspath(self.dir1)  # 获取绝对路径
        self.dir2path = os.path.abspath(self.dir2)
    
    def comparedir(self, dirpath, dir2path):
        holderlist = []
        dircomp = filecmp.dircmp(dirpath, dir2path)

        only_in_one = [os.path.abspath(os.path.join(dirpath, x)) for x in dircomp.left_only]
        diff_in_one_left = [os.path.abspath(os.path.join(dir2path, x)) for x in dircomp.diff_files]
        holderlist.extend(only_in_one)
        holderlist.extend(diff_in_one_left)

        if len(dircomp.common_dirs) > 0:
            for item in dircomp.common_dirs:
                subdir_diff = self.comparedir(os.path.join(dirpath, item), os.path.join(dir2path, item))
                holderlist.extend(subdir_diff)
        
        return holderlist
    
    def main(self):
        source_files = self.comparedir(self.dirpath, self.dir2path)

        if not self.dir2.endswith('/'):
            self.dir2 += '/'
        
        dest_files = []
        creatdir_bool = False
        
        for item in source_files:
            dest_dir = re.sub(self.dirpath, self.dir2, item)
            dest_files.append(dest_dir)
            
            if not os.path.exists(os.path.dirname(dest_dir)):
                os.makedirs(os.path.dirname(dest_dir))
                creatdir_bool = True
        
        if creatdir_bool:
            dest_files = []
            source_files = self.comparedir(self.dir1, self.dir2)
            
            for item in source_files:
                dest_dir = re.sub(self.dirpath, self.dir2, item)
                dest_files.append(dest_dir)
                
                if not os.path.exists(os.path.dirname(dest_dir)):
                    os.makedirs(os.path.dirname(dest_dir))
                else:
                    shutil.copy(item, dest_dir)

        print("update items:", source_files)

if __name__ == '__main__':
    dir1 = '/home/backup/FULL-2024-03-29_12-00'
    dir2 = '/home/backup/FULL-2024-03-28_12-03'
    A = CompareArgs(dir1, dir2)
    A.main()